//
//  PostViewController.m
//  Gruphoto
//
//  Created by Thao Nguyen Huy on 1/4/13.
//  Copyright (c) 2013 CNC Software. All rights reserved.
//

#import "PostViewController.h"
#import "EventLargeCell.h"
#import "ODRefreshControl.h"
#import "EventDetailViewController.h"
#import "MapViewController.h"
#import "GruphotoAppDelegate.h"
#import "User.h"
#import "Event.h"
#import "Photo.h"

@implementation UINavigationBar (CustomImage)
- (void)drawRect:(CGRect)rect {
    UIImage *image = [UIImage imageNamed:@"background_navigation_bar.png"];
    [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}
@end

@interface PostViewController ()
- (void)addBarItems;
- (void)resignKeyboard;
@end

@implementation PostViewController

@synthesize postTableView, postSearchBar, maskView;
@synthesize refreshControl, postedEvents, eventsNeedDisplay, selectedEvent;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:226/255.0 green:231/255.0 blue:237/255.0 alpha:1.0];
    postSearchBar.backgroundImage = [UIImage imageNamed:@"background_searchbar.png"];
    [self addBarItems];
    postTableView.bounces = YES;
    refreshControl = [[ODRefreshControl alloc] initInScrollView:postTableView];
    [refreshControl addTarget:self action:@selector(dropViewDidBeginRefreshing:) forControlEvents:UIControlEventValueChanged];
    
    [self getPostedEvents];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    self.postSearchBar = nil;
    self.postTableView = nil;
    self.maskView = nil;
}

- (void)dealloc {
    self.selectedEvent = nil;
    self.eventsNeedDisplay = nil;
    self.postedEvents = nil;
    self.refreshControl = nil;
    [postSearchBar release];
    [postTableView release];
    [maskView release];
    [super dealloc];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Private methods
- (void)addBarItems {
    UIButton *mapButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [mapButton setBounds:CGRectMake(0, 0, 51, 30)];
    [mapButton setBackgroundImage:[UIImage imageNamed:@"button_map.png"] forState:UIControlStateNormal];
    [mapButton addTarget:self action:@selector(mapButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *mapButtonItem = [[UIBarButtonItem alloc] initWithCustomView:mapButton];
    self.navigationItem.rightBarButtonItem = mapButtonItem;
    [mapButtonItem release];
}

- (void)resignKeyboard {
    [postSearchBar resignFirstResponder];
    maskView.hidden = YES;
}

#pragma mark - Custom methods
- (void)getPostedEvents {
    [[GruphotoAppDelegate sharedDelegate] showHUDWithStatus:@"Loading..."];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:[GruphotoAppDelegate sharedDelegate].loggedInUser.token forKey:kUserToken];
    //    NSNumber *longitue = [NSNumber numberWithDouble:[GruphotoAppDelegate sharedDelegate].currentLocation.coordinate.longitude];
    //    NSNumber *latitude = [NSNumber numberWithDouble:[GruphotoAppDelegate sharedDelegate].currentLocation.coordinate.latitude];
    //    [params setObject:longitue forKey:kLongitude];
    //    [params setObject:latitude forKey:kLatitude];
    NSLog(@"params: %@", params);
    [TNHRequestHelper sendPostRequest:kGetPostedEventUrl
                              withTag:RequestTaggetPostedEvents
                               params:params
                             delegate:self];    
}

- (void)resetSearch {
    
}

- (void)handleSearchForTerm:(NSString *)searchTerm {
    
}

#pragma mark - Action methods
- (IBAction)mapButtonPressed:(id)sender {
    [self resignKeyboard];
    MapViewController *mapViewController = [[MapViewController alloc] initWithNibName:@"MapViewController" bundle:nil];
    mapViewController.mapMode = EventMapModeSearch;
    whereEventCome = EventDetailModePost;
    mapViewController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:mapViewController animated:YES];
    [mapViewController release];
    mapViewController = nil;
}


- (IBAction)maskViewTapped:(id)sender {
    [self resignKeyboard];
}

#pragma mark - ODRefreshControl
- (void)dropViewDidBeginRefreshing:(ODRefreshControl *)_refreshControl
{
    double delayInSeconds = 3.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [_refreshControl endRefreshing];
    });
}

#pragma mark - UISearchBarDelegate
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    maskView.hidden = NO;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [self resignKeyboard];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return eventsNeedDisplay.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *LargeCellId = @"EventLargeCell";
    EventLargeCell *cell = (EventLargeCell *)[tableView dequeueReusableCellWithIdentifier:LargeCellId];
    if (cell == nil) {
        cell = [EventLargeCell cellFromNib];
    }
    return cell;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    EventDetailViewController *eventDetailViewController = [[EventDetailViewController alloc] initWithNibName:@"EventDetailViewController" bundle:nil];
    eventDetailViewController.hidesBottomBarWhenPushed = YES;
    eventDetailViewController.detailMode = EventDetailModePost;
    [self.navigationController pushViewController:eventDetailViewController animated:YES];
    [eventDetailViewController release];
}

#pragma mark - ASIHTTPRequestDelegate
- (void)requestFinished:(ASIHTTPRequest *)request {
    [[GruphotoAppDelegate sharedDelegate] hideHUD];
    NSDictionary *response = (NSDictionary *)[TNHRequestHelper objectWithString:request.responseString];
    NSInteger errorCode = [[response objectForKey:kErrorCode] integerValue];
    if (errorCode == ErrorCodeNone) {
        NSLog(@"listEvent data: %@", response);
        if (request.tag == RequestTagGetLiveEvents) {
            self.postedEvents = [NSMutableArray array];
            NSArray *events = [response objectForKey:kEvents];
            for (NSDictionary *dict in events) {
                Event *event = [[Event alloc] init];
                event.eventId = [[dict objectForKey:kEventId] integerValue];
                event.eventTitle = [dict objectForKey:kTitle];
                event.placeName = [dict objectForKey:kPlaceName];
                event.placeAddress = [dict objectForKey:kPlaceAddress];
                event.longitude = [dict objectForKey:kLongitude];
                event.latitude = [dict objectForKey:kLatitude];
                event.eventEnd = [[dict objectForKey:kTimeLimit] integerValue];
                event.eventPasstime = [[dict objectForKey:kPassTime] integerValue];
                event.numberOfImages = [[dict objectForKey:kNumPhoto] integerValue];
                event.numberOfLikes = [[dict objectForKey:kNumLike] integerValue];
                event.numberOfMembers = [[dict objectForKey:kNumMember] integerValue];
                event.isPrivate = ![[dict objectForKey:kIsPublic] boolValue];
                event.code = [dict objectForKey:kCode];
                event.distance = [[dict objectForKey:kDistance] floatValue];
                event.isJoining = [[dict objectForKey:kJoining] boolValue];
                NSDictionary *dictUser = [dict objectForKey:kUser];
                User *creater = [[User alloc] init];
                creater.userId = [[dictUser objectForKey:kUserId] integerValue];
                creater.firstName = [dictUser objectForKey:kFirstName];
                creater.lastName = [dictUser objectForKey:kLastName];
                if (![[dictUser objectForKey:kPhoto] isEqual:[NSNull null]]) {
                    creater.avatarUrl = [dictUser objectForKey:kPhoto];
                    if ([creater.avatarUrl rangeOfString:@"http" options:NSCaseInsensitiveSearch].location == NSNotFound ||
                        [creater.avatarUrl rangeOfString:@"https" options:NSCaseInsensitiveSearch].location == NSNotFound) {
                        creater.avatarUrl = [NSString stringWithFormat:@"%@%@", kServerUrl, creater.avatarUrl];
                    }
                }
                if (![[dictUser objectForKey:kSocialId] isEqual:[NSNull null]]) {
                    creater.socialId = [dictUser objectForKey:kSocialId];
                }
                creater.numberOfFollowers = [[dictUser objectForKey:kNumFollower] integerValue];
                creater.numberOfLikes = [[dictUser objectForKey:kNumLike] integerValue];
                creater.numberOfPhotos = [[dictUser objectForKey:kNumPhoto] integerValue];
                event.creater = creater;
                [creater release];
                
                NSArray *photos = [response objectForKey:kImages];
                for (NSString *urlString in photos) {
                    if ([urlString rangeOfString:@"http" options:NSCaseInsensitiveSearch].location == NSNotFound ||
                        [urlString rangeOfString:@"https" options:NSCaseInsensitiveSearch].location == NSNotFound) {
                        urlString = [NSString stringWithFormat:@"%@%@", kServerUrl, urlString];
                    }
                    Photo *_photo = [[Photo alloc] initWithSourcePath:urlString];
                    [event.photos addObject:_photo];
                    [_photo release];
                    [[SDWebImageManager sharedManager] downloadWithURL:[NSURL URLWithString:urlString] delegate:nil options:0];
                }
                [postedEvents addObject:event];
                [event release];
            }
            [postedEvents sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
                Event *event1 = (Event *)obj1;
                Event *event2 = (Event *)obj2;
                return event1.distance > event2.distance;
            }];
            [self resetSearch];
            [postTableView reloadData];
        }
        else if (request.tag == RequestTagGetDetailsOfEvent) {
            NSLog(@"one event data: %@", response);
            EventDetailViewController *eventDetailViewController = [[EventDetailViewController alloc] initWithNibName:@"EventDetailViewController" bundle:nil];
            eventDetailViewController.eventDetail = response;
            eventDetailViewController.hidesBottomBarWhenPushed = YES;
            //            eventDetailViewController.detailMode = EventDetailModeJoin;
            //            selectedEvent.numberOfImages = [[response objectForKey:kNumPhoto] integerValue];
            //            selectedEvent.numberOfMembers = [[response objectForKey:kNumMember] integerValue];
            //            selectedEvent.numberOfLikes = [[response objectForKey:kNumLike] integerValue];
            //            selectedEvent.eventPasstime = [[response objectForKey:kPassTime] integerValue];
            NSArray *arrayUsers = [response objectForKey:@"users"];
            for (NSDictionary *user in arrayUsers) {
                User *member = [[User alloc] init];
                member.firstName = [user objectForKey:kFirstName];
                member.lastName = [user objectForKey:kLastName];
                member.numberOfFollowers = [[user objectForKey:kNumFollower] integerValue];
                member.numberOfLikes = [[user objectForKey:kNumLike] integerValue];
                member.numberOfPhotos = [[user objectForKey:kNumPhoto] integerValue];
                if (![[user objectForKey:kPhoto] isEqual:[NSNull null]]) {
                    member.avatarUrl = [user objectForKey:kPhoto];
                    if ([member.avatarUrl rangeOfString:@"http" options:NSCaseInsensitiveSearch].location == NSNotFound ||
                        [member.avatarUrl rangeOfString:@"https" options:NSCaseInsensitiveSearch].location == NSNotFound) {
                        member.avatarUrl = [NSString stringWithFormat:@"%@%@", kServerUrl, member.avatarUrl];
                    }
                }
                member.userId = [[user objectForKey:kUserId] integerValue];
                if (![[user objectForKey:kSocialId] isEqual:[NSNull null]]) {
                    member.socialId = [user objectForKey:kSocialId];
                }
                //                [selectedEvent.users addObject:member];
                [member release];
            }
            eventDetailViewController.event = selectedEvent;
            [self.navigationController pushViewController:eventDetailViewController animated:YES];
            NSArray *viewControllers = [NSArray arrayWithObject:[self.navigationController.viewControllers lastObject]];
            [self.navigationController setViewControllers:viewControllers animated:NO];
            [eventDetailViewController release];
        }
    }
    else {
        NSString *errorMessage = [response objectForKey:kErrorMessage];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error message"
                                                            message:errorMessage
                                                           delegate:nil
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
        [alertView show];
        [alertView release];
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request {
    [[GruphotoAppDelegate sharedDelegate] hideHUD];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Connection error"
                                                        message:@"Internet is down, please try again"
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
    [alertView show];
    [alertView release];
}

@end
